import cgi
import re
import datetime
import hashlib
import errors

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import images
from google.appengine.ext.webapp import template

import appengine_admin
from xml.etree.ElementTree import parse, fromstring, XML
from django.utils import simplejson as json 


salt = '3Eb7k'
from models import *

#method to conv to boolean
def str2bool(v):
    return v.lower() in ("yes", "true", "t", "1")

def input2none(i):
    if str(i).lower() == "none":
	return None
    else:
	return i

def optionalargsjson(obj,field,):
    try:
        return obj[field]
    except:
	return None

"""
helper methods for the registering of user in tranx
 -registeruserwithlocationxml
 -registeruserwithlocationjson

args: 
"""

def registerbizwithlocationxml(parsed, businesstype):
        location = parsed.find('location')
        password1 = parsed.find('password').text  
        newbiz = Gabusiness(  
		    bizname = parsed.find('bizname').text,
		    biztype = businesstype,
		    contactemail = parsed.find('contactemail').text,
		    contactname = parsed.find('contactname').text,
		    phonenumber = parsed.find('phonenumber').text,
		    #password = hashlib.sha256(salt + password1).hexdigest(),
		    password = password1,
		    is_active = str2bool(parsed.find('is_active').text),
        )
	if parsed.find('faxnumber') != None:
	    newbiz.faxnumber = input2none(parsed.find('faxnumber').text)
	if parsed.find('url') != None:
	    newbiz.url = input2none(parsed.find('url').text)
	if parsed.find('supportemail') != None:
	    newbiz.supportemail = input2none(parsed.find('supportemail').text)
      
        newbiz.put()

        if location != None:
                newlocation = Gabizlocation(  parent = newbiz, 
			    	gabusiness = newbiz,
			    	geopoint = input2none(location.find('geocode').text),
			    	address = location.find('address').text,
			    	city = location.find('city').text,
			    	state = location.find('state').text,
			    	zipcode = location.find('zipcode').text,
			    	country = location.find('country').text,
			    	#modified_by =
                )
                newlocation.put()
	return newbiz.key().id()

def registerbizwithlocation(inbizname, inbusinesstype, incontactemail, incontactname, inphonenumber, inpassword, infaxnumber, insupportemail, inurl, ingeopoint, inaddress, incity, instate, inzipcode, incountry):
        # data is collected so create the user entity and location entity
        password1 = inpassword
        newbiz = Gabusiness(  
		    bizname = inbizname,
		    biztype = inbusinesstype,
		    contactemail = incontactemail,
		    contactname = incontactname,
		    phonenumber = inphonenumber, 
		    #password = hashlib.sha256(salt + password1).hexdigest(),
		    password = password1,
		    faxnumber = infaxnumber,
		    supportemail = insupportemail,
		    url = inurl,
        )
        newbiz.put()
      
        newlocation = Gabizlocation(  parent = newbiz, 
			    	gabusiness = newbiz,
			    	geopoint = input2none(ingeopoint),
			    	address = inaddress, 
			    	city = incity,
			    	state = instate,
			    	zipcode = inzipcode, 
			    	country = incountry,
			    	#modified_by =
        )
        newlocation.put()
	return newbiz.key().id()

class BizCreationPage(webapp.RequestHandler):
   #delete just puts is_active as false... no actual delete
    def options(self, version):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return

    def delete(self, version):
        header = self.request.headers['Content-Type']
        if "application/json" in header:
	    reqobj = json.loads(self.request.body)
	    reqbiz = reqobj['businessaccount']
	    bizaccount = {}
	    bizaccount['businessaccount'] = {}
	    biz = Gabusiness.get_by_id( int (reqbiz['id']) )
	    if biz != None:
		try:
	            biz.is_active = str2bool( 'False')
	            biz.put()
	            bizaccount['businessaccount']['result'] = biz.key().id()
		except:
		     bizaccount['businessaccount']['result'] = -1
	    else:
	        bizaccount['businessaccount']['result'] = -2	

	    self.response.out.write( json.dumps(bizaccount) )
	    return
	    

    def post(self, version):
        header = self.request.headers['Content-Type']
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"        
	#this could be any type of form
        if "multipart/form-data" in header:
	    hashpwd =  hashlib.sha256(salt + str(self.request.get('password')))    
            userbirthday = datetime.date(int(self.request.get('year')), int(self.request.get('month')), int(self.request.get('date')))
	    try:
	        user = Gauser(  email = self.request.get('email'),
			    firstname = self.request.get('firstname'),
			    lastname = self.request.get('lastname'),
			    currentzip = self.request.get('currentzip'),
			    gender = str(self.request.get('gender')),
			    birthday = userbirthday, #birthday[i].text, convert it to dateself.request.get('birthday'),
			    username = self.request.get('username'),
			    #password = hashpwd.hexdigest(),
			    password = self.request.get('password'), 
			    is_public = str2bool(self.request.get('is_public')),
			    is_calendar_shared = str2bool(self.request.get('is_calendar_shared')),
	        )

  	    except ValueError: 
		self.redirect('/home/user')
		return
    	    if self.request.get('image'):
	        user.image = self.request.get('image')        
	
	    user.put()
            self.redirect('/home')
	    return   

        elif "text/xml" in header:
	    requiredkeys = set(['businessaccount','bizname', 'businesstype', 'contactemail', 'contactname', 'phonenumber', 'password', 'location', 'address', 'city', 'state', 'zipcode', 'country'])
	    keys = set(['businessaccount','bizname', 'businesstype', 'contactemail', 'contactname', 'phonenumber', 'supportemail', 'faxnumber', 'url' ,'password', 'location', 'geocode', 'address', 'city', 'state', 'zipcode', 'country'])
	    self.response.headers['Content-Type'] = "text/xml"
	    self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>"""
	    )
	    parsed = fromstring(self.request.body)
	    xmlkeys = set([a.tag for a in parsed.getiterator()] )
	    if requiredkeys.issubset(xmlkeys):  # checking if it has all required fields
		#if xmlkeys.issubset(keys):	#checking if xml doesn't have any unnecessary fields
		    	bizname = parsed.findtext('bizname')
		    	contactemail = parsed.findtext('contactemail')
		    	contactname = parsed.findtext('contactname')
		    	phonenumber = parsed.findtext('phonenumber')
		    	password = parsed.findtext('password') 
		    	biztypeid = parsed.findtext('businesstype')

		    	location = parsed.find('location')

		    	address = location.findtext('address')
		    	city = location.findtext('city')
		    	state = location.findtext('state')
		    	zipcode = location.findtext('zipcode')
		    	country = location.findtext('country')

	    		faxnumber = parsed.findtext('faxnumber') 
	    		supportemail = parsed.findtext('supportemail') 
	    		url = parsed.findtext('url') 
	    		geopoint = location.findtext('geocode') 

	    		biztype = Gabusinesstype.get_by_id(int(biztypeid))
	   		if biztype != None:
	        	        checkbiz = db.GqlQuery("SELECT __key__ FROM Gabusiness WHERE bizname = :1", bizname)
	       		        if checkbiz.count() == 0:
	            			try:
	                	    		result = db.run_in_transaction(registerbizwithlocation, bizname, biztype, contactemail, contactname, phonenumber, password, faxnumber, supportemail, url, geopoint, address, city, state, zipcode, country)
            			    		self.response.out.write(
"""
<businessaccount>
    <result>
	<code>%s</code>
	<message>%s</message>
    </result>
</businessaccount>""" % (result, errors.returnerror['created'] % ('business', result) )
	                	    		)	 
	            			except:
				    		self.response.out.write(
"""
<businessaccount>
    <result>
	<code>%s</code>
	<message>%s</message>
    </result>
</businessaccount>""" % (-1, errors.returnerror['transactionfail'])
	                	    		)	 
	        	        else:
		    		    	self.response.out.write(
"""
<businessaccount>
    <result>
	<code>%s</code>
	<message>%s</message>
    </result>
</businessaccount>""" % (-2, errors.returnerror['exists'] % ('bizname', bizname) )
	            			)		
	   		else:
			    self.response.out.write(
"""
<businessaccount>
    <result>
	<code>%s</code>
	<message>%s</message>
    </result>
</businessaccount>""" % (-2, errors.returnerror['noidfound'] % ('businesstype',biztypeid))
	            	    )		
	    else:
		neededkeys = requiredkeys - xmlkeys
	        self.response.out.write(
"""
<businessaccount>
    <result>
	<code>%s</code>
	<message>%s</message>
    </result>
</businessaccount>""" % (-1, errors.returnerror['field'] % (neededkeys.pop(), 'business') ) #[a for a in neededkeys] all required keys
	        )	    
	    return	

        elif "application/json" in header:
 	    self.response.headers['Content-Type'] = "application/json"
	    bizaccount = {}
	    bizaccount['businessaccount'] = {}
	    reqobj = json.loads(self.request.body)
	    try:
	    	reqbiz = reqobj['businessaccount']
	    except KeyError, e:
		bizaccount['businessaccount']['result'] = {'code':-1, 'message':(errors.returnerror['accountfield'] % e) }
		self.response.out.write( json.dumps(bizaccount) )
	   	return
	    try:
		    bizname = reqbiz['bizname']
		    contactemail = reqbiz['contactemail'] 
		    contactname = reqbiz['contactname']
		    phonenumber = reqbiz['phonenumber']
		    password = reqbiz['password']
		    location = reqbiz['location']
		    biztypeid = reqbiz['businesstype']
	    except KeyError, e:
		    bizaccount['businessaccount']['result'] = {'code':-1, 'message':(errors.returnerror['field'] % (e, 'business')) }
		    self.response.out.write( json.dumps(bizaccount) )
	    	    return
	    try:
		    address = location['address']
		    city = location['city']
		    state = location['state']
		    zipcode = location['zipcode']
		    country = location['country']
	    except KeyError, e:
		    bizaccount['businessaccount']['result'] = {'code':-1, 'message':errors.returnerror['field'] % (e, 'business location' )}
		    self.response.out.write( json.dumps(bizaccount) )
	    	    return
	    faxnumber = optionalargsjson(reqbiz, 'faxnumber') 
	    supportemail = optionalargsjson(reqbiz, 'supportemail') 
	    url = optionalargsjson(reqbiz, 'url') 
	    geopoint = optionalargsjson(location, 'geocode') 	

	    biztype = Gabusinesstype.get_by_id(int(biztypeid) )
	    if biztype != None:
	        checkbiz = db.GqlQuery("SELECT __key__ FROM Gabusiness WHERE bizname = :1", bizname)
	        if checkbiz.count() == 0:
	            try:
	                result = db.run_in_transaction(registerbizwithlocation, bizname, biztype, contactemail, contactname, phonenumber, password, faxnumber, supportemail, url, geopoint, address, city, state, zipcode, country)
		        bizaccount['businessaccount']['result'] = {'code':result, 'message':errors.returnerror['created'] % ('business', result) }
	            except:
		        bizaccount['businessaccount']['result'] = {'code':-1, 'message':errors.returnerror['transactionfail'] }
	        else:
		    bizaccount['businessaccount']['result'] = {'code':-2, 'message':errors.returnerror['exists'] % ('bizname', bizname) }
	    else:
		bizaccount['businessaccount']['result'] = {'code':-2, 'message':errors.returnerror['noidfound'] % ('businesstype',biztypeid) }
	    self.response.out.write( json.dumps(bizaccount) )
	    return
	else:
	    #if not json, xml, or multi-part form data
	    return

#Update Business

class BizUpdate(webapp.RequestHandler):
	#probably don't need the ID since ID is already inside the body of the request
    def options(self, version, ID):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return    
	def post(self, version):
	    header = self.request.headers['Content-Type']
	    body = self.request.body
	    #if version == 'v1':  
	    if 'text/xml' in header:
	        self.response.headers['Content-Type'] = "text/xml"
	        self.response.out.write(
"""
<?xml version="1.0" encoding='utf-8'?>
<useraccount>"""
		)  
	        # do some xml parsing of user
	        parsed = fromstring(body)
	        reqbizid = parsed.find('id').text
                #reqbizname = parsed.find('bizname').text
		#reqbusinesstype = Gabusinesstype.get_by_id(int(parsed.find('businesstype').text)
		reqcontactemail = parsed.find('contactemail').text
		reqcontactname = parsed.find('contactname').text
		requrl = parsed.find('url').text
		reqsupportemail = parsed.find('supportemail').text
	 	reqphonenumber = parsed.find('phonenumber').text
		#password = hashlib.sha256(salt + password1).hexdigest()
		reqpassword = parsed.find('password').text
		reqis_active = parsed.find('is_active').text
		reqlocation = parsed.find('location')

	        biz = Gabusiness.get_by_id(int(reqbizid))  #this or ID
	        #what gets sent in an update request?
	        if biz != None:

		    #associationstoadd = []
		    #locationstoadd = []

		    #biz.bizname = reqbizname
		    #biz.businesstype = reqbusinesstype
		    biz.contactemail = reqcontactemail
		    biz.contactname = reqcontactname
		    biz.url = requrl
		    biz.supportemail = reqsupportemail
		    biz.phonenumber = reqphonenumber
		    biz.password = reqpassword
		    biz.is_active = str2bool(reqis_active)

		    if reqlocation != None:
			updatelocation = Gabizlocation.get_by_id(int( reqlocation.find('id') ))
			if updatelocation != None:
			    updatelocation.geopoint = reqlocation.find('geopoint').text
			    updatelocation.address =  reqlocation.find('address').text
			    updatelocation.city = reqlocation.find('city').text
			    updatelocation.state = reqlocation.find('state').text
			    updatelocation.zipcode = reqlocation.find('zipcode').text
			    updatelocation.country = reqlocation.find('country').text

                	    updatelocation.put()

		    user.put()
			    			
		    self.response.out.write(
"""<result>0</result>"""
		    )
		else:
    		    self.response.out.write(
"""<result>-1</result>"""
		    )
		

	    #if version == 'v2':
	    # might have to combine the version check and header check
	    elif 'application/json' in header:
	        reqobj = json.loads(self.request.body)
 	        self.response.headers['Content-Type'] = "application/json"
	        bizaccount = {}
	        bizaccount['businessaccount'] = {}
		#reqobj is the dictionary that was sent
	        # {'user': {'id': id#, 'firstname': name ,...  } }

		#need to check if dictionary has all the objects?
		#checking if dictionaries have all the ekys

		
		if 'businessaccount' in reqobj:
			reqbiz = reqobj['businessaccount']
			biz = Gabusiness.get_by_id( int( requser['id'] ) )
			if biz != None:
		   		#biz.bizname = reqbiz['bizname']
		    		#biz.businesstype = reqbiz['businesstype']
				
		    		biz.contactemail = reqbiz['contactemail']
		    		biz.contactname = reqbiz['contactname']
		    		biz.url = reqbiz['url']
		    		biz.supportemail = reqbiz['supportemail']
		    		biz.phonenumber = reqbiz['phonenumber']
		    		biz.password = reqbiz['password']
		    		biz.is_active = str2bool(reqbiz['is_active'] )

				if reqbiz['location'] != None:
				    updatelocation = Gabizlocation.get_by_id( int(reqbiz['location']['id'] ))
				    
			    	    updatelocation.geopoint = reqbiz['location']['geopoint']
			    	    updatelocation.address =  reqbiz['location']['address']
			    	    updatelocation.city = reqbiz['location']['city']
			    	    updatelocation.state = reqbiz['location']['state']
			    	    updatelocation.zipcode = reqbiz['location']['zipcode']
			    	    updatelocation.country = reqbiz['location']['country']

                	    	    updatelocation.put()
			        try:
				    biz.put()
				    bizaccount['businessaccount']['result'] = biz.key().id()

			        except:
				    bizaccount['businessaccount']['result'] = -1

			else: 
			    bizaccount['businessaccount']['result'] = -2
		        
			self.response.out.write( json.dumps(useraccount) )

		else:
		    self.response.out.write("user object is missing")	
		    return		
		
	        #for key, value in reqobj.iteritems():
	    else:
		#not json or xml
		return


class BusinessAuthenticate(webapp.RequestHandler):
	def options(self, version):
		self.response.headers['Content-Type'] = "application/json"
		self.response.headers['Access-Control-Allow-Origin'] = "*"
		self.response.headers['Vary'] = "Origin"
		self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
		self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
		return     

	def post(self, version):
		header = self.request.headers['Content-Type']
		body = self.request.body
		if 'text/xml' in header:
	    		requiredkeys = set(['businessaccount','bizname', 'password',])
	    		self.response.headers['Content-Type'] = "text/xml"
	    		self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>"""
	    		)
	    		parsed = fromstring(body)
	    		xmlkeys = set([a.tag for a in parsed.getiterator()] )
	   		if requiredkeys.issubset(xmlkeys):  # checking if it has all required fields
				reqbizname = parsed.findtext('bizname')
				reqpassword = parsed.findtext('password')
				gabusiness = Gabusiness.all().filter('bizname =', reqbizname).get()
				if gabusiness!=None:
				    if gabusiness.password == reqpassword:
					self.response.out.write(
"""
<businessaccount>
    <result>
	<code>%s</code>
	<message>%s</message>
    </result>
</businessaccount>""" % (gabusiness.key().id(), errors.returnerror['signinpass'] % reqbizname )
					)
				    else:
					self.response.out.write(
"""
<businessaccount>
    <result>
	<code>%s</code>
	<message>%s</message>
    </result>
</businessaccount>""" % (-1, errors.returnerror['signinfail']  )
					)
				else:
				    self.response.out.write(
"""
<businessaccount>
    <result>
	<code>%s</code>
	<message>%s</message>
    </result>
</businessaccount>""" % (-2, errors.returnerror['notexists'] % ('bizname', reqbizname))
				    )
			else:
				#not all required keys
				neededkeys = requiredkeys - xmlkeys
	        		self.response.out.write(
"""
<businessaccount>
    <result>
	<code>%s</code>
	<message>%s</message>
    </result>
</businessaccount>""" % (-1, errors.returnerror['field'] % (neededkeys.pop(), 'business sign in') ) #[a for a in neededkeys] all required keys
	        		)
		    	return

		elif 'application/json' in header:
			self.response.headers['Content-Type'] = "application/json"
			self.response.headers['Access-Control-Allow-Origin'] = "*"
			self.response.headers['Vary'] = "Origin"
			self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
			self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"
			
	   		businessaccount = {}
			businessaccount['businessaccount'] = {}
			reqobj = json.loads(body)			
	    		try:
	    			reqbiz = reqobj['businessaccount']
	   		except KeyError, e:
				businessaccount['businessaccount']['result'] = {'code':-1, 'message':(errors.returnerror['accountfield'] % e) }
				self.response.out.write( json.dumps(businessaccount) )
	   			return
			try:
				reqbizname = reqbiz['bizname']
				reqpassword = reqbiz['password']
			except KeyError, e:
				businessaccount['businessaccount']['result'] = {'code':-1, 'message':(errors.returnerror['field'] % (e, 'business')) }
		    		self.response.out.write( json.dumps(businessaccount) )
	    	    		return

			gabusiness = Gabusiness.all().filter('bizname = ', reqbizname).get()
			if gabusiness != None:
				if gabusiness.password == reqpassword:
					businessaccount['businessaccount']['result'] = {'code':gabusiness.key().id(), 'message':errors.returnerror['signinpass'] % reqbizname}
				else:
					businessaccount['businessaccount']['result'] = {'code':-1, 'message':errors.returnerror['signinfail']  }
			else:
				businessaccount['businessaccount']['result'] = {'code':-2 , 'message':errors.returnerror['notexists'] % ('bizname', reqbizname)}
			self.response.out.write( json.dumps(businessaccount) )
                	return
		else:
			#not v1 or v2
			return



class BusinessTypeList(webapp.RequestHandler):
    def options(self, version):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return    
    def get(self, version):
        businesstypes = Gabusinesstype.all().order('gabusinesstype')

	if version == 'v1':
	    self.response.headers['Content-Type'] = "text/xml"
            self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<businesstypes>"""
	    )
            for businesstype in businesstypes:
		    self.response.out.write(
"""    
        <businesstype>"""
		    )
		    self.response.out.write(
"""
	    <businesstypeid>%s</businesstypeid>
	    <businesstypename>%s</businesstypename>
	    <date_updated>%s</date_updated>""" % (businesstype.key().id() , businesstype.gabusinesstype , businesstype.date_updated )
	            )
	            self.response.out.write(
"""
        </businesstype>""" 
	            )
	    self.response.out.write(
"""
</businesstypes>""")
	    return

	elif version == 'v2':
	    self.response.headers['Content-Type'] = "application/json"
	    self.response.headers['Content-Type'] = "application/json"
	    self.response.headers['Access-Control-Allow-Origin'] = "*"
	    self.response.headers['Vary'] = "Origin"
	    self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
	    self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"
        
	    businessaccount = {}
	    businessaccount['businesstypes'] = []
            for businesstype in businesstypes:
		    temptype =	{
				'businesstypeid': businesstype.key().id(),
				'businesstypename': businesstype.gabusinesstype,
				'date_updated': businesstype.date_updated,
				}

		    businessaccount['businesstypes'].append(temptype)

            self.response.out.write( json.dumps(businessaccount) )

	else:
	    # will have to enter v1 or v2. nothing else should go through
	    return

#full business info
class BusinessInfo(webapp.RequestHandler):
    def options(self, version, ID):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return    
    def get(self, version, ID):
        biz= Gabusiness.get_by_id(int(ID))
	if version == 'v1':
	    self.response.headers['Content-Type'] = "text/xml"
            self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<businessaccount>"""
	        )
            if biz != None:
                self.response.out.write(
"""    
	<id>%s</id>
	<bizname>%s</bizname>
	<contactemail>%s</contactemail>
	<contactname>%s</contactname>
	<url>%s</url>
	<supportemail>%s</supportemail>
	<phone>%s</phone>
	<fax>%s</fax>
	<is_active>%s</is_active>
	<date_updated>%s</date_updated>""" % (biz.key().id(), biz.bizname , biz.contactemail, biz.contactname, biz.url, biz.supportemail, biz.phonenumber, biz.faxnumber, biz.is_active, biz.date_updated)
	        )
	
	        if biz.image:
	            self.response.out.write(
"""
	<image><img src='/img?img_id=%s&amp;size=%s'></img></image>""" % (biz.key(), str(200) )
	            )
	
	    #all businesses should have one location so these checks might not be needed
	    #this biz location might also need a date updated like the event location
	        if (biz.business_locations).count():
                    self.response.out.write(
"""
        <location>""")
                    for bizlocation in biz.business_locations:
	                self.response.out.write(
"""
			<geocode>%s</geocode>
			<address>%s</address>
			<city>%s</city>
			<state>%s</state>
			<zip>%s</zip>
			<country>%s</country>
""" % (bizlocation.geopoint, bizlocation.address, bizlocation.city, bizlocation.state, bizlocation.zipcode, bizlocation.country)
		        )
	                self.response.out.write(
"""
	</location>""")
	    else:
		    self.response.out.write(
"""
	<result>no matching biz id</result>"""
		    )
	    self.response.out.write(
"""
</businessaccount>"""
	        )
	    return

	elif version == 'v2':
	    self.response.headers['Content-Type'] = "application/json"
	    self.response.headers['Access-Control-Allow-Origin'] = "*"
	    self.response.headers['Vary'] = "Origin"
	    self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
	    self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
	    businessaccount = {}
	    #should add an else clause to this if biz is empty
	    if biz != None:
	        tempbiz =	{
			'id': biz.key().id(),
			'bizname': biz.bizname ,
			'contactemail': biz.contactemail,
			'contactname': biz.contactname, 
			'url': biz.url,
			'supportemail': biz.supportemail,
			'phone': biz.phonenumber, 
			'fax': biz.faxnumber,
			'is_active': biz.is_active,
			'date_updated': biz.date_updated,
			    	}

                if biz.image:
		    tempbiz['image'] = biz.key()

	        #all businesses should have one location so these checks might not be needed
	        #this biz location might also need a date updated like the event location
	        if (biz.business_locations).count():
		    tempbiz['location'] = []
                    for bizlocation in biz.business_locations:
		        temploc =	{
				'geocode': bizlocation.geopoint,
				'address': bizlocation.address,
				'city': bizlocation.city,
				'state': bizlocation.state,
				'zip': bizlocation.zipcode,
				'country': bizlocation.country,
					}
		        tempbiz['location'].append( temploc)
	    	businessaccount['businessaccount'] = tempbiz
	    else:
		businessaccount['businessaccount'] = {'result': "No business by that name"}
            self.response.out.write( json.dumps(businessaccount) )
	    return

	else:
	    #if it is not v1 or v2
	    return
	


#given list of business ids return info
class BusinessListInfo(webapp.RequestHandler):
    def options(self, version, ids):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return    
    def get(self, version, ids):
        stringlistofids = re.split("%2C", ids) #%2C is esc char for ,
	intlistofids = [ int(each) for each in stringlistofids]
	if version == 'v1':
	    self.response.headers['Content-Type'] = "text/xml"
            self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<businesses>"""	
	    )
	    if intlistofids:
	        bizs = Gabusiness.get_by_id(intlistofids)
	        for biz in bizs:
		    if biz != None:
		        self.response.out.write(
"""
	<business>"""
		        )
	                self.response.out.write(
"""	    <id>%s</id>
	    <bizname>%s</bizname>
	    <contactemail>%s</contactemail>
	    <contactname>%s</contactname>
	    <url>%s</url>
	    <supportemail>%s</supportemail>
	    <phone>%s</phone>
	    <fax>%s</fax>
	    <is_active>%s</is_active>
	    <date_updated>%s</date_updated>""" % (biz.key().id(), biz.bizname , biz.contactemail, biz.contactname, biz.url, biz.supportemail, biz.phonenumber, biz.faxnumber, biz.is_active, biz.date_updated)
		        )
		
             	        if biz.image:
			    self.response.out.write(
"""
	<image><img src='/img?img_id=%s&amp;size=%s'></img></image>""" % (biz.key(), str(200) )
	              	    )	
		      	
	                if (biz.business_locations).count():
                            self.response.out.write(
"""
	    <location>"""
		    	    )
                            for bizlocation in biz.business_locations:
	                        self.response.out.write(
"""
		<geocode>%s</geocode>
	        <address>%s</address>
	        <city>%s</city>
	        <state>%s</state>
	        <zip>%s</zip>
	        <country>%s</country>""" % (bizlocation.geopoint, bizlocation.address, bizlocation.city, bizlocation.state, bizlocation.zipcode, bizlocation.country)
			        )
	                    self.response.out.write(
"""
	    </location>"""
	                    )
		        self.response.out.write(
"""
	</business>"""
		        )
            self.response.out.write(
"""
</businesses>"""
	    )
	    return

	elif version == 'v2':
	    self.response.headers['Content-Type'] = "application/json"
	    self.response.headers['Access-Control-Allow-Origin'] = "*"
	    self.response.headers['Vary'] = "Origin"
	    self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
	    self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
	    businessaccount = {}
	    businessaccount['businesses'] = []
	    if intlistofids:
	        bizs = Gabusiness.get_by_id(intlistofids)
	        for biz in bizs:
		    if biz != None:
	    	    #should add an else clause to this if biz is empty
	    	        tempbiz =	{
				'id': biz.key().id(),
				'bizname': biz.bizname ,
				'contactemail': biz.contactemail,
				'contactname': biz.contactname, 
				'url': biz.url,
				'supportemail': biz.supportemail,
				'phone': biz.phonenumber, 
				'fax': biz.faxnumber,
				'is_active': biz.is_active,
				'date_updated': biz.date_updated,
				     }

             	        if biz.image:
			    tempbiz['image'] = biz.key()
	
	                if (biz.business_locations).count():
			    tempbiz['location'] = []
                            for bizlocation in biz.business_locations:
			        temploc =	{
				'geocode': bizlocation.geopoint,
				'address': bizlocation.address,
				'city': bizlocation.city,
				'state': bizlocation.state,
				'zip': bizlocation.zipcode,
				'country': bizlocation.country,
					        }
			        tempbiz['location'].append( temploc)

		        businessaccount['businesses'].append( tempbiz)

	    self.response.out.write( json.dumps(businessaccount) )
	    return

	else:
	    #not v1 or v2 
	    return


#full business info lite version
class BusinessLiteInfo(webapp.RequestHandler):
    def options(self, version, ID):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return    
    def get(self, version, ID):
        biz= Gabusiness.get_by_id(int(ID))
	if version == 'v1':
	    self.response.headers['Content-Type'] = "text/xml"
            self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<businessaccount>"""
	    )
            self.response.out.write(
"""    
	<id>%s</id>
	<bizname>%s</bizname>
	<is_active>%s</is_active>
	<date_updated>%s</date_updated>""" % (biz.key().id(), biz.bizname, biz.is_active, biz.date_updated)
	    )
            if biz.image:
	        self.response.out.write(
"""
	<image><img src='/img?img_id=%s&amp;size=%s'></img></image>""" % (biz.key(), str(200) )
	        )		
	    #all businesses should have one location so these checks might not be needed
	    if (biz.business_locations).count():
               self.response.out.write(
"""
	<location>"""
	        )
	       for bizlocation in biz.business_locations:
	   	    self.response.out.write(
"""
			<geocode>%s</geocode>
			<address>%s</address>
			<city>%s</city>
			<state>%s</state>
			<zip>%s</zip>
			<country>%s</country>""" % (bizlocation.geopoint, bizlocation.address, bizlocation.city, bizlocation.state, bizlocation.zipcode, bizlocation.country)
		    )
	            self.response.out.write(
"""
	</location>"""
		    )
            self.response.out.write(
"""
</businessaccount>"""
	    )  
	    return
	elif version == 'v2':
	    self.response.headers['Content-Type'] = "application/json"
	    self.response.headers['Access-Control-Allow-Origin'] = "*"
	    self.response.headers['Vary'] = "Origin"
	    self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
	    self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
	    businessaccount = {}
	    #should add an else clause to this if biz is empty
	    tempbiz =	{
			'id': biz.key().id(),
			'bizname': biz.bizname ,
			'is_active': biz.is_active,
			'date_updated': biz.date_updated,
			}

            if biz.image:
		tempbiz['image'] = biz.key()

	    #all businesses should have one location so these checks might not be needed
	    #this biz location might also need a date updated like the event location
	    if (biz.business_locations).count():
		tempbiz['location'] = []
                for bizlocation in biz.business_locations:
		    temploc =	{
				'geocode': bizlocation.geopoint,
				'address': bizlocation.address,
				'city': bizlocation.city,
				'state': bizlocation.state,
				'zip': bizlocation.zipcode,
				'country': bizlocation.country,
				}
		    tempbiz['location'].append( temploc)
	    businessaccount['businessaccount'] = tempbiz
            self.response.out.write( json.dumps(businessaccount) )
	    return
	else:
	    #if it is not v1 or v2
	    return



#given list of business ids return lite info
class BusinessListLiteInfo(webapp.RequestHandler):
    def options(self, version, ids):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return    
    def get(self, version, ids):
        stringlistofids = ids.split("%2C") #%2C is esc char for 
	intlistofids = [ int(each) for each in stringlistofids]
	if version == 'v1':
	    self.response.headers['Content-Type'] = "text/xml"
            self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<businesses>"""	
	    )
	    if intlistofids:
	        bizs = Gabusiness.get_by_id(intlistofids)
		for biz in bizs:
		    if biz != None:
		        self.response.out.write(
"""
	<business>"""
		        )
	                self.response.out.write(
"""
	    <id>%s</id>
	    <bizname>%s</bizname>
	    <is_active>%s</is_active>
	    <date_updated>%s</date_updated>""" % (biz.key().id(), biz.bizname , biz.is_active, biz.date_updated)
		        )
		        if biz.image:
		            self.response.out.write(
"""
	<image><img src='/img?img_id=%s&amp;size=%s'></img></image>""" % (biz.key(), str(200) )
		            )		
		
	                if (biz.business_locations).count():
                            self.response.out.write(
"""
	    <location>"""
		            )
                            for bizlocation in biz.business_locations:
	                        self.response.out.write(
"""
		<geocode>%s</geocode>
	        <address>%s</address>
	        <city>%s</city>
	        <state>%s</state>
	        <zip>%s</zip>
	        <country>%s</country>""" % (bizlocation.geopoint, bizlocation.address, bizlocation.city, bizlocation.state, bizlocation.zipcode, bizlocation.country)
			        )
	                    self.response.out.write(
"""
	    </location>"""
		            )
		        self.response.out.write(
"""
	</business>"""
		        )
            self.response.out.write(
"""
</businesses>"""
	    )
	    return

	elif version == 'v2':
	    self.response.headers['Content-Type'] = "application/json"
	    self.response.headers['Access-Control-Allow-Origin'] = "*"
	    self.response.headers['Vary'] = "Origin"
	    self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
	    self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
	    businessaccount = {}
	    businessaccount['businesses'] = []
	    if intlistofids:
		bizs = Gabusiness.get_by_id(intlistofids)
	        for biz in bizs:
		    if biz != None:
	    		#should add an else clause to this if biz is empty
	    	        tempbiz =	{
				'id': biz.key().id(),
				'bizname': biz.bizname ,
				'is_active': biz.is_active,
				'date_updated': biz.date_updated,
					}

             	        if biz.image:
			    tempbiz['image'] = biz.key()
	
	                if (biz.business_locations).count():
			    tempbiz['location'] = []
                            for bizlocation in biz.business_locations:
			        temploc =	{
				'geocode': bizlocation.geopoint,
				'address': bizlocation.address,
				'city': bizlocation.city,
				'state': bizlocation.state,
				'zip': bizlocation.zipcode,
				'country': bizlocation.country,
					 	}
			        tempbiz['location'].append( temploc)

		        businessaccount['businesses'].append( tempbiz)

	    self.response.out.write( json.dumps(businessaccount) )
	    return

	else:
	    #not v1 or v2 
	    return

#list of businesses
class BusinessesList(webapp.RequestHandler):
    def options(self):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return
    def get(self):
        bizs= Gabusiness.all()
	self.response.headers['Content-Type'] = "text/xml"
        self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<businesses>
"""
	)
	for biz in bizs:
	    self.response.out.write("	    <account>")
            self.response.out.write(
"""    
		<id>%s</id>
		<bizname>%s</bizname>
		<businesstype>%s</businesstype>
		<contactemail>%s</contactemail>
		<contactname>%s</contactname>
		<url>%s</url>
		<ein>%s</ein>
		<supportemail>%s</supportemail>
		<phone>%s</phone>
		<fax>%s</fax>
		<is_active>%s</is_active>
		<date_updated>%s</date_updated>""" % (biz.key().id(), biz.bizname,  biz.biztype , biz.contactemail, biz.contactname, biz.url, biz.ein, biz.supportemail, biz.phonenumber, biz.faxnumber, biz.is_active, biz.date_updated)
	    )
	    if (biz.business_locations).count():
                self.response.out.write(
"""
		<location>"""
		)
                for bizlocation in biz.business_locations:
	            self.response.out.write(
"""			
			<geocode>%s</geocode>
			<address>%s</address>
			<city>%s</city>
			<state>%s</state>
			<zip>%s</zip>
			<country>%s</country>""" % (bizlocation.geopoint, bizlocation.address, bizlocation.city, bizlocation.state, bizlocation.zipcode, bizlocation.country)
		    )
		self.response.out.write(
"""
		</location>"""
		)
	    self.response.out.write(
"""	    
	    </account>"""
	    )     
        self.response.out.write(
"""
</businesses>"""
	)

#location of an event given businessid
class BusinessLocation(webapp.RequestHandler):
    def options(self, version, ID):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return    
    def get(self, version, ID):
        biz = Gabusiness.get_by_id(int(ID))
	if version == 'v1':
	    self.response.headers['Content-Type'] = "text/xml"
            self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<businessaccount>"""
	    )
	    if biz != None:
                self.response.out.write(
"""    
	<id>%s</id>""" % biz.key().id()
	        )
	        #all businesses should have one location so these checks might not be needed
	        if (biz.business_locations).count():
                    self.response.out.write(
"""
	<location>"""
		    )
                    for bizlocation in biz.business_locations:

	                self.response.out.write(
"""
		<geocode>%s</geocode>
		<address>%s</address>
		<city>%s</city>
		<state>%s</state>
		<zip>%s</zip>
		<country>%s</country>""" % (bizlocation.geopoint, bizlocation.address, bizlocation.city, bizlocation.state, bizlocation.zipcode, bizlocation.country)
		        )
	                self.response.out.write(
"""
	</location>"""
		        )
		
            self.response.out.write(
"""
</businessaccount>"""
	    )
	    return

	elif version == 'v2':
	    self.response.headers['Content-Type'] = "application/json"
	    self.response.headers['Access-Control-Allow-Origin'] = "*"
	    self.response.headers['Vary'] = "Origin"
	    self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
	    self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
	    businessaccount = {}

	    if biz != None:  
	        tempbiz = {
			'id': biz.key().id(),
			  }

	        #all businesses should have one location so these checks might not be needed
	        if (biz.business_locations).count():
		    tempbiz['location'] = []
                    for bizlocation in biz.business_locations:
			temploc = 	{
				'geocode': bizlocation.geopoint,
				'address': bizlocation.address,
				'city': bizlocation.city,
				'state': bizlocation.state,
				'zip': bizlocation.zipcode,
				'country': bizlocation.country,
					}
			tempbiz['location'].append( temploc)
		businessaccount['businessaccount'] = tempbiz

	    else:
		businessaccount['businessaccount'] = None

	    self.response.out.write(json.dumps(businessaccount) )
            return

	else:
	    #not v1 or v2
	    return

def deleteeventtranx(eventkey):
    children = db.GqlQuery("SELECT * WHERE ANCESTOR IS :1", eventkey)
    for each in children:
	each.delete()
    return 1

class DeleteBusinessEvents(webapp.RequestHandler):

    def delete(self, version, bizid, ids):
            stringlistofids = ids.split("%2C")
	    intlistofids = [ int(each) for each in stringlistofids] 

	    if version == 'v1':
	        self.response.headers['Content-Type'] = "text/xml"
	        self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<businessaccount>""")
	        biz = Gabusiness.get_by_id( int(bizid) )
	    	if biz != None:
		    self.response.out.write(
"""
    <results>""")
		    for eachid in intlistofids:
			event = Gaevent.get_by_id(eachid)
			if event != None:
			    if event.gabusiness.key() == biz.key():
	            	        try:            
			            db.run_in_transaction(deleteeventtranx, event.key())
			            self.response.out.write(
"""
        <result>%s</result>""" %  eachid)
		    	        except:
			            self.response.out.write(
"""
	<result>-1</result>""")
			    else:
				self.response.out.write(
"""
	<result>event %s does not match business %s"</result>""" % (eachid, biz.key().id()))
			else:
			    self.response.out.write(
"""
	<result>no event with id %s</result>""" % eachid)
		    self.response.out.write(
"""
    </results>""")
	    	else:
		    self.response.out.write(
"""
    <result>-2</result>""")
	    	self.response.out.write(
"""
</businessaccount>""")
	    	return  

	    elif version == 'v2':
	        self.response.headers['Content-Type'] = "application/json"
	        businessaccount = {}
	        businessaccount['businessaccount'] = {}
		businessaccount['businessaccount']['result'] = []
	    	biz = Gabusiness.get_by_id( int(bizid) )
	    	if biz != None:
		    for eachid in intlistofids: 
			event = Gaevent.get_by_id(eachid)
			if event != None:
			    if event.gabusiness.key() == biz.key():
	            	        try:            
			            db.run_in_transaction(deleteeventtranx, event.key())
			            businessaccount['businessaccount']['result'].append( eachid)
		    	        except:
			            businessaccount['businessaccount']['result'].append(-1)
			    else:
				businessaccount['businessaccount']['result'].append("event %s does not match business %s" % (eachid, biz.key().id()) )
			else:
			    businessaccount['businessaccount']['result'].append("no event with id %s" %eachid)
	    	else:
		    businessaccount['businessaccount']['result'] = -2
	    	self.response.out.write(json.dumps( businessaccount))
	    	return  

class BusinessEvents(webapp.RequestHandler):
    def options(self, version, ID):
        self.response.headers['Content-Type'] = "application/json"
        self.response.headers['Access-Control-Allow-Origin'] = "*"
        self.response.headers['Vary'] = "Origin"
        self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
        self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
        return    
    def get(self, version, ID):
        biz = Gabusiness.get_by_id(int(ID))
	if version == 'v1':
	    self.response.headers['Content-Type'] = "text/xml"
            self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<businessaccount>"""
	    )	
	    if biz != None:
                self.response.out.write(
"""    
    <id>%s</id>""" % biz.key().id()
	        )
	        #all businesses should have one location so these checks might not be needed
	        if (biz.business_events).count():
                    self.response.out.write(
"""
    <events>"""
                    )
                    for bizevents in biz.business_events:
	                self.response.out.write(
"""
            <eventid>%s</eventid>""" % (bizevents.key().id())
		        )
		    self.response.out.write(
"""
    </events>"""
	            )
            self.response.out.write(
"""
</businessaccount>"""
	    )
	    return

	elif version == 'v2':
	    self.response.headers['Content-Type'] = "application/json"
	    self.response.headers['Access-Control-Allow-Origin'] = "*"
	    self.response.headers['Vary'] = "Origin"
	    self.response.headers['Access-Control-Allow-Methods'] = "OPTIONS, GET, POST, PUT, DELETE"
	    self.response.headers['Access-Control-Allow-Headers'] = "Content-Type"           
	    businessaccount = {}
	    if biz != None:
	        tempbiz = 	{ 
			'id': biz.key().id(),
				}
	        tempbiz['events'] = []
	        #all businesses should have one location so these checks might not be needed
	        if (biz.business_events).count():
                    for bizevents in biz.business_events:
		        tempevent = {
				'eventid': bizevents.key().id(),
				    }
		        tempbiz['events'].append( tempevent )
	        businessaccount['businessaccount'] = tempbiz

	    else:
		businessaccount['businessaccount'] =  None
	    self.response.out.write( json.dumps(businessaccount) )
	    return

	else:
	    #not v1 or v2
	    return

    def delete(self, version):
	    header = self.request.headers['Content-Type']
	    body = self.request.body	   
	    if 'text/xml' in header:
	        parsed = fromstring(body)
	        self.response.headers['Content-Type'] = "text/xml"
	        self.response.out.write(
"""<?xml version="1.0" encoding='utf-8'?>
<businessaccount>""")
	        reqbizid = parsed.find('id').text
	        eventids = parsed.find('events')
	        ids = eventids.findall('eventid')
	        biz = Gabusiness.get_by_id( int(reqbizid) )
	    	if biz != None:
		    self.response.out.write(
"""
    <results>""")
		    for eachid in ids: 
			event = Gaevent.get_by_id(eachid)
			if event != None:
			    if event.gabusiness.key() == biz.key():
	            	        try:            
			            db.run_in_transaction(deleteeventtranx, event.key())
			            self.response.out.write(
"""
        <result>%s</result>""" %  eachid.text)
		    	        except:
			            self.response.out.write(
"""
	<result>-1</result>""")
			    else:
				self.response.out.write(
"""
	<result>%s</result>""" % "event does not match business")
			else:
			    self.response.out.write(
"""
	<result>no event with id %s</result>""" % eachid.text)
		    self.response.out.write(
"""
    </results>""")
	    	else:
		    self.response.out.write(
"""
    <result>-2</result>""")
	    	self.response.out.write(
"""
</businessaccount>""")
	    	return  

	    elif 'application/json' in header:
	        self.response.headers['Content-Type'] = "application/json"
	        businessaccount = {}
	        businessaccount['businessaccount'] = {}
		businessaccount['businessaccount']['result'] = []

		reqobj = json.loads(body)
	        reqbiz = reqobj['businessaccount']
	
	    	reqbizid = reqbiz['id']
	    	ids = reqbiz['events']
	    	biz = Gabusiness.get_by_id( int(reqbizid) )
	    	if biz != None:
		    for eachid in ids: 
			event = Gaevent.get_by_id(eachid)
			if event != None:
			    if event.gabusiness.key() == biz.key():
	            	        try:            
			            db.run_in_transaction(deleteeventtranx, event.key())
			            businessaccount['businessaccount']['result'].append( eachid)
		    	        except:
			            businessaccount['businessaccount']['result'].append(-1)
			    else:
				businessaccount['businessaccount']['result'].append("event does not match business")
			else:
			    businessaccount['businessaccount']['result'].append("no event with id %s" %eachid)
	    	else:
		    businessaccount['businessaccount']['result'] = -2
	    	self.response.out.write(json.dumps( businessaccount))
	    	return  
	    


    def post(self, version):
	    header = self.request.headers['Content-Type']
	    body = self.request.body
	    #if version == 'v1':  
	    if 'text/xml' in header:
	        self.response.headers['Content-Type'] = "text/xml"
	        self.response.out.write(
"""
<?xml version="1.0" encoding='utf-8'?>
<businessaccount>"""
		)  
	        # do some xml parsing of user
	        parsed = fromstring(body)
	        reqbusinessid = parsed.find('id').text

	        businessevents = parsed.find('events')
	        events = businessevents.findall('event')

	        biz = Gabusiness.get_by_id(int(reqbusinessid))  #this or ID
	        if biz != None:
		    for event in events:
			if event != None:
				savedlocations = event.find('savedlocations')
				if savedlocations != None:
            			    locations = savedlocations.findall('location') 
				categories = event.find('categories')
				if categories != None:
				    category = categories.findall('category')
			        reqeventstartdate = event.find('eventstartdate').text
			        reqeventenddate = event.find('eventenddate').text
			        reqeventstarttime = event.find('eventstarttime').text
			        reqeventendtime = event.find('eventendtime').text
			        eventexpiration = event.find('eventexpiration').text

			        is_active = event.find('is_active').text
			        is_featured = event.find('is_featured').text
			        price = event.find('price').text  
				
				newevent = Gaevent( 
						gabusiness = biz,
						gabusinessid = biz.key().id(),
						eventname = event.find('eventname').text,
						eventdescription = event.find('eventdescription').text,
						tickets = event.find('tickets').text,
						supportemail = event.find('supportemail').text,
						supportphone = event.find('supportphone').text,
						eventstartdate = datetime.date(int(reqeventstartdate[0:4]), int(reqeventstartdate[5:7]), int(reqeventstartdate[8:10]) ),
						eventenddate = datetime.date(int(reqeventenddate[0:4]), int(reqeventenddate[5:7]), int(reqeventenddate[8:10]) ),
						eventstarttime = datetime.time(int(reqeventstarttime[0:2]), int(reqeventstarttime[3:4])),
						eventendtime = datetime.time(int(reqeventendtime[0:2]), int(reqeventendtime[3:4])),
						eventexpiration = datetime.datetime(int(reqeventenddate[0:4]), int(reqeventenddate[5:7]), int(reqeventenddate[8:10]), int(reqeventendtime[0:2]), int(reqeventendtime[3:4]) ),
						eventstartdatetime = datetime.datetime(int(reqeventstartdate[0:4]), int(reqeventstartdate[5:7]), int(reqeventstartdate[8:10]),int(reqeventstarttime[0:2]), int(reqeventstarttime[3:4])  ),
						eventenddatetime = datetime.datetime(int(reqeventenddate[0:4]), int(reqeventenddate[5:7]), int(reqeventenddate[8:10]), int(reqeventendtime[0:2]), int(reqeventendtime[3:4]) ),
						is_active = int(event.find('is_active').text),
						is_featured = str2bool(event.find('is_featured').text),
						price = event.find('price').text,
				)
				newevent.put()
				if savedlocations != None:
				    for location in locations:
					
					newlocation = Gaeventlocation(
						parent = newevent,
						gaevent = newevent,
						geopoint= location.find('geocode').text,
						address=location.find('address').text,
						city=location.find('city').text,
						state=location.find('state').text,
						zipcode=location.find('zip').text,
						country=location.find('country').text,
    						eventstartdatetime = datetime.datetime(int(reqeventstartdate[0:4]), int(reqeventstartdate[5:7]), int(reqeventstartdate[8:10]),int(reqeventstarttime[0:2]), int(reqeventstarttime[3:4])  ),
    						eventenddatetime = datetime.datetime(int(reqeventenddate[0:4]), int(reqeventenddate[5:7]), int(reqeventenddate[8:10]), int(reqeventendtime[0:2]), int(reqeventendtime[3:4]) ),
					)
					newlocation.put()
					newevent.eventgeopoint = location.find('geocode').text 
					newevent.put()

				if categories != None:
					for eachcategory in category:
					    cat = Gacategory.get_by_id(int(eachcategory.find('categoryid').text) )
					    if cat != None:
					        newcategory = Gaeventcategory(
							parent = newevent,
							gaevent = newevent,
							gacategory = cat,
							eventstartdatetime = datetime.datetime(int(reqeventstartdate[0:4]), int(reqeventstartdate[5:7]), int(reqeventstartdate[8:10]),int(reqeventstarttime[0:2]), int(reqeventstarttime[3:4])  ),
    							eventenddatetime = datetime.datetime(int(reqeventenddate[0:4]), int(reqeventenddate[5:7]), int(reqeventenddate[8:10]), int(reqeventendtime[0:2]), int(reqeventendtime[3:4]) ),
						)
						newcategory.put()
						if cat.categoryparentname:
						    newevent.eventcategories.append(cat.categoryparentname.key().id() )
						newevent.eventcategories.append(int(eachcategory.find('categoryid').text))
						newevent.put()
				self.response.out.write(
"""
    <result>%s</result>""" % newevent.key().id()
				)
			else:
			    self.response.out.write(
"""
    <result>no events</result>""")
	        else:
		    self.response.out.write(
"""
    <result>no biz</result>""")
		self.response.out.write("""
</businessaccount>""")
		return

	    elif 'application/json' in header:
	        self.response.headers['Content-Type'] = "application/json"
	        businessaccount = {}
	        businessaccount['businessaccount'] = {}
		businessaccount['businessaccount']['result'] = []

		reqobj = json.loads(self.request.body)
	        reqbiz = reqobj['businessaccount']
		if 'events' in reqbiz:
		    events = reqbiz['events']

	            biz = Gabusiness.get_by_id( int (reqbiz['id']) )
	            if biz != None:
		        for event in events:
			    try:
				if 'savedlocations' in event:
            			    savedlocations = event['savedlocations']
				else:
				    savedlocations = None
				if 'categories' in event:
				    categories = event['categories']
				else:
				    categories = None
			        reqeventstartdate = event['eventstartdate']
			        reqeventenddate = event['eventenddate']
			        reqeventstarttime = event['eventstarttime']
			        reqeventendtime = event['eventendtime']
			        eventexpiration = event['eventexpiration']		
				newevent = Gaevent( 
						gabusiness = biz,
						gabusinessid = biz.key().id(),
						eventname = event['eventname'],
						eventdescription = event['eventdescription'],		
						eventstartdate = datetime.date(int(reqeventstartdate[0:4]), int(reqeventstartdate[5:7]), int(reqeventstartdate[8:10]) ),
						eventenddate = datetime.date(int(reqeventenddate[0:4]), int(reqeventenddate[5:7]), int(reqeventenddate[8:10]) ),
						eventstarttime = datetime.time(int(reqeventstarttime[0:2]), int(reqeventstarttime[3:4])),
						eventendtime = datetime.time(int(reqeventendtime[0:2]), int(reqeventendtime[3:4])),
						eventexpiration = datetime.datetime(int(reqeventenddate[0:4]), int(reqeventenddate[5:7]), int(reqeventenddate[8:10]), int(reqeventendtime[0:2]), int(reqeventendtime[3:4]) ),
						eventstartdatetime = datetime.datetime(int(reqeventstartdate[0:4]), int(reqeventstartdate[5:7]), int(reqeventstartdate[8:10]),int(reqeventstarttime[0:2]), int(reqeventstarttime[3:4])  ),
						eventenddatetime = datetime.datetime(int(reqeventenddate[0:4]), int(reqeventenddate[5:7]), int(reqeventenddate[8:10]), int(reqeventendtime[0:2]), int(reqeventendtime[3:4]) ),
						is_active = int(event['is_active']),
						is_featured = str2bool(event['is_featured']),
						
				)
				if 'tickets' in event:
				    newevent.tickets = event['tickets']
				if 'price' in event:
				    newevent.price = event['price']
				if 'supportemail' in event:
				    newevent.supportemail = supportemail = event['supportemail']
				if 'supportphone' in event:
				    newevent.supportphone = event['supportphone']
				if categories != None:
				    cat = Gacategory.get_by_id(int(categories[0]['categoryid']) )
				    if cat != None:
					newevent.gacategory = cat
				    else:
					businessaccount['businessaccount']['result'].append("categoryid %s is not valid. biz not registered" % categories[0]['categoryid'] )
					self.response.out.write( json.dumps(businessaccount) )
					return
				newevent.put()

				if len(categories) > 1:
					for eachcategory in categories[1:]:
					    cat = Gacategory.get_by_id(int(eachcategory['categoryid']) )
					    if cat != None:
					        newcategory = Gaeventcategory(
							gaevent = newevent,
							gacategory = cat,
							eventstartdatetime = datetime.datetime(int(reqeventstartdate[0:4]), int(reqeventstartdate[5:7]), int(reqeventstartdate[8:10]),int(reqeventstarttime[0:2]), int(reqeventstarttime[3:4])  ),
    							eventenddatetime = datetime.datetime(int(reqeventenddate[0:4]), int(reqeventenddate[5:7]), int(reqeventenddate[8:10]), int(reqeventendtime[0:2]), int(reqeventendtime[3:4]) ),
						)
						newcategory.put()
						if cat.categoryparentname:
						    newevent.eventcategories.append(cat.categoryparentname.key().id() )
						newevent.eventcategories.append(int(eachcategory['categoryid']))

				if savedlocations != None:
				    for location in savedlocations:
					
					newlocation = Gaeventlocation(
						parent = newevent,
						gaevent = newevent,
						geopoint= location['geocode'],
						address=location['address'],
						city=location['city'],
						state=location['state'],
						zipcode=location['zip'],
						country=location['country'],
    						eventstartdatetime = datetime.datetime(int(reqeventstartdate[0:4]), int(reqeventstartdate[5:7]), int(reqeventstartdate[8:10]),int(reqeventstarttime[0:2]), int(reqeventstarttime[3:4])  ),
    						eventenddatetime = datetime.datetime(int(reqeventenddate[0:4]), int(reqeventenddate[5:7]), int(reqeventenddate[8:10]), int(reqeventendtime[0:2]), int(reqeventendtime[3:4]) ),
					)
					newlocation.put()
					newevent.eventgeopoint = location['geocode']
				newevent.put()

				businessaccount['businessaccount']['result'].append( newevent.key().id() )
			    except:
				businessaccount['businessaccount']['result'].append( -1 )
	            else:
		        businessaccount['businessaccount']['result']= -2
		else:
		    businessaccount['businessaccount']['result']= 'json obj not correct format'
	        self.response.out.write( json.dumps(businessaccount) )
		return
	    else:
		return


#Image class page
class ImagePage (webapp.RequestHandler):
    def get(self):
        user = db.get(self.request.get("img_id"))
        if user.image:
            self.response.headers['Content-Type'] = "image/png"
	    theimage = images.resize(user.image, 50,50)
            self.response.out.write(theimage)
        else:
            self.response.out.write("No image")

application = webapp.WSGIApplication([
    (r'^/rest/v1/business/img', ImagePage), #needs to be implemented
    (r'^/rest/(v1|v2)/business/register$', 		BizCreationPage),
    (r'^/rest/(v1|v2)/business/signin$',	 	BusinessAuthenticate),
    (r'^/rest/(v1|v2)/business/businesstypes/list$', 	BusinessTypeList),
    (r'^/rest/(v1|v2)/business/update/?$', 		BizUpdate),
    (r'^/rest/(v1|v2)/business/id/(.*)/?$', 		BusinessInfo ),
    (r'^/rest/(v1|v2)/business/lite/id/(.*)/?$', 	BusinessLiteInfo ),
    (r'^/rest/(v1|v2)/business/location/id/(.*)/?$', 	BusinessLocation),
    (r'^/rest/v1/business/list/?$', 			BusinessesList),
    (r'^/rest/(v1|v2)/business/list/ids/(.*)/?$', 	BusinessListInfo ),
    (r'^/rest/(v1|v2)/business/list/lite/ids/(.*)/?$', 	BusinessListLiteInfo ),
    (r'^/rest/(v1|v2)/business/events/id/(.*)/deleteids/(.*)/?$', DeleteBusinessEvents),
    (r'^/rest/(v1|v2)/business/events/id/(.*)/?$', 	BusinessEvents ),
    (r'^/rest/(v1|v2)/business/events?$', 		BusinessEvents ),
], debug=True)


def main():
    run_wsgi_app(application)


if __name__ == '__main__':
    main()
